package com.kevis.zhunblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kevis.zhunblog.core.dto.sys.SysMenu;
import com.kevis.zhunblog.core.entities.PowerMenuEntity;
import com.kevis.zhunblog.mapper.PowerMenuMapper;
import com.kevis.zhunblog.mapper.RolePowerMapper;
import com.kevis.zhunblog.service.PowerMenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class PowerMenuServiceImpl extends ServiceImpl<PowerMenuMapper, PowerMenuEntity>
        implements PowerMenuService {

    /**
     * 引入服务
     */
    @Resource
    private PowerMenuMapper powerMenuMapper;

    /**
     * 引入角色权限服务
     */
    @Resource
    private RolePowerMapper rolePowerMapper;

    @Override
    public List<SysMenu> getUserMenu(String username) {
        if (!StringUtils.hasLength(username))
            return null;
        List<SysMenu> result = new ArrayList<SysMenu>();
        LambdaQueryWrapper<PowerMenuEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PowerMenuEntity::getIsShow, 1);
        //超管查询全部
        if ("admin".equalsIgnoreCase(username)) {
            List<PowerMenuEntity> list = baseMapper.selectList(lambdaQueryWrapper);
            if (list != null && list.size() > 0) {
                List<SysMenu> collect = list.stream().map(p -> {
                    SysMenu menu = new SysMenu();
                    menu.setHref(p.getUrl());
                    menu.setIcon(p.getIcon());
                    menu.setId(p.getId());
                    menu.setOpenType(p.getOpenType());
                    menu.setParentId(p.getParentId());
                    menu.setTitle(p.getTitle());
                    menu.setType(p.getMenuType());
                    //result.add(menu);
                    return menu;
                }).collect(Collectors.toList());
                result = collect;
            }
        }
        return result;
    }

    /**
     * 将菜单转为树形结构
     *
     * @param sysMenus
     * @param parentId
     * @return
     */
    @Override
    public List<SysMenu> toTreeUserMenu(List<SysMenu> sysMenus, Integer parentId) {
        //public List<SysMenu> toTreeUserMenu(List<SysMenu> sysMenus, String parentId) {
        ArrayList<SysMenu> list = new ArrayList<>();
        for (SysMenu menu : sysMenus) {
            menu.setHref(com.kevis.common.constant.ServletConstant.SERVER_SERVLET_CONTEXTPATH + "/zhun/post.do?actionguid=" + menu.getGuid());
            if (parentId.equals(menu.getParentId())) {
                menu.setChildren(toTreeUserMenu(sysMenus, menu.getId()));
                list.add(menu);
            }
        }
        return list;
    }

    @Override
    public List<SysMenu> getMenuList() {
        List<SysMenu> result = new ArrayList<SysMenu>();
        List<PowerMenuEntity> list = baseMapper.selectList(null);
        if (list != null && list.size() > 0) {
            List<SysMenu> collect = list.stream().map(p -> {
                SysMenu menu = new SysMenu();
                menu.setHref(p.getUrl());
                menu.setIcon(p.getIcon());
                menu.setId(p.getId());
                menu.setOpenType(p.getOpenType());
                menu.setParentId(p.getParentId());
                menu.setTitle(p.getTitle());
                menu.setType(p.getMenuType());
                //result.add(menu);
                return menu;
            }).collect(Collectors.toList());
            result = collect;
        }
        return result;
    }

    /**
     * 根据url和menucode获取菜单
     *
     * @param url
     * @param menuCode
     * @return
     */
    @Override
    public PowerMenuEntity getByUrlMenuCode(String url, String menuCode) {
        if (!StringUtils.hasLength(url) || !StringUtils.hasLength(menuCode)) return null;
        PowerMenuEntity entity = lambdaQuery()
                .eq(PowerMenuEntity::getStatus, 0)
                .eq(PowerMenuEntity::getIsShow, 1)
                .eq(PowerMenuEntity::getUrl, url)
                .eq(PowerMenuEntity::getMenuCode, menuCode)
                .one();
        return entity;
    }

    /**
     * 根据url返回菜单实体
     *
     * @param url
     * @return
     */
    @Override
    public PowerMenuEntity getByUrl(String url) {
        if (!StringUtils.hasLength(url)) {
            return null;
        }
        PowerMenuEntity entity = lambdaQuery()
                //.select(PowerMenuEntity::getId)
                .eq(PowerMenuEntity::getStatus, 0)
                .eq(PowerMenuEntity::getIsShow, 1)
                .eq(PowerMenuEntity::getUrl, url)
                .last("limit 1")
                .one();
        return entity;
    }

    /**
     * 根据列表的菜单地址以及按钮的标识进行查询按钮的实体
     *
     * @param url
     * @param menuCode
     * @return
     */
    @Override
    public PowerMenuEntity getByListUrlAndMenuCode(String url, String menuCode) {
        if (!StringUtils.hasLength(url) || !StringUtils.hasLength(menuCode)) return null;
        //先返回列表的菜单
        PowerMenuEntity listEntity = getByUrl(url);
        if (listEntity == null || listEntity.getId() == null) return null;
        PowerMenuEntity entity = lambdaQuery()
                .eq(PowerMenuEntity::getStatus, 0)
                .eq(PowerMenuEntity::getIsShow, 1)
                .eq(PowerMenuEntity::getParentId, listEntity.getId())
                .eq(PowerMenuEntity::getMenuCode, menuCode)
                .last("limit 1")
                .one();
        return entity;
    }

    /**
     * Describe: 查询权限列表
     * Param: SysPower
     * Return: 执行结果
     */
    @Override
    public List<PowerMenuEntity> list(PowerMenuEntity sysPower) {
        return baseMapper.selectList(new QueryWrapper<>(sysPower));
    }

    /**
     * Describe: 根据 parentId 查询权限
     * Param: parentId
     * Return: 操作结果
     */
    @Override
    public List<PowerMenuEntity> selectByParentId(String parentId) {
        LambdaQueryWrapper<PowerMenuEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PowerMenuEntity::getParentId, parentId);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<PowerMenuEntity> listMenu(PowerMenuEntity sysPower) {
        LambdaQueryWrapper<PowerMenuEntity> wrapper = new LambdaQueryWrapper<PowerMenuEntity>(sysPower);
        wrapper.ne(PowerMenuEntity::getMenuType, "2");
        return baseMapper.selectList(wrapper);
    }

    /**
     * Describe: 根据 ID 删除权限信息
     * Param: id
     * Return: 执行结果
     * rollbackFor: 默认只在遇到运行时异常和Error时才会回滚，非运行时异常不回滚
     * 而rollbackFor属性可以解决这个问题，rollbackFor = Exception.class表示Exception及其子类的异常都会触发回滚，同时不影响Error的回滚。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean remove(String id) {
        powerMenuMapper.deleteById(id);
        rolePowerMapper.deleteByPowerId(id);
        return true;
    }

    @Override
    public boolean existsByUrl(String url) {
        if (!StringUtils.hasLength(url)) {
            return false;
        }
        PowerMenuEntity entity = lambdaQuery().select(PowerMenuEntity::getId)
                .eq(PowerMenuEntity::getStatus, 0).eq(PowerMenuEntity::getUrl, url).last("limit 1").one();
        return null != entity && entity.getId() > 0;
    }

    /************************************************************/
    @Override
    public PowerMenuEntity getByMenuCode(String actionGuid, String menuCode) {
        if (!StringUtils.hasLength(actionGuid) || !StringUtils.hasLength(menuCode)) return null;
        PowerMenuEntity entity = lambdaQuery()
                .eq(PowerMenuEntity::getStatus, 0)
                //.eq(PowerMenuEntity::getIsShow, 1)
                .eq(PowerMenuEntity::getGuid, actionGuid)
                //.eq(PowerMenuEntity::getMenuCode, menuCode)
                .one();
        if (entity != null && entity.getId() > 0)
            return lambdaQuery()
                    .eq(PowerMenuEntity::getStatus, 0)
                    .eq(PowerMenuEntity::getParentId, entity.getId())
                    .eq(PowerMenuEntity::getMenuCode, menuCode)
                    .one();
        return null;
        //return entity;
    }
}




